import normalizeHeader from './helpers/normalizeHeader';
import buildURL, { resolveURL } from './helpers/buildURL';

const axios = function axios(config) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open(
            config.method,
            buildURL(resolveURL(config.baseURL, config.url), config.params),
            true
        );

        const normalizeHeaders = normalizeHeader(config.header);

        normalizeHeaders.forEach(([name, value]) => {
            // 设置请求头
            xhr.setRequestHeader(name, value);
        });

        xhr.onreadystatechange = function onreadystatechange() {
            if (xhr.readyState !== xhr.DONE) {
                return false;
            }

            const responseHeaders = xhr.getAllResponseHeaders();
            const responseData = xhr.response;
            const response = {
                data: responseData,
                status: xhr.status,
                statusText: xhr.statusText,
                request: xhr,
                headers: responseHeaders,
                config: config
            };

            resolve(response);
        };

        let requestData = config.data || null;
        requestData = requestData ? JSON.stringify(requestData) : null;

        xhr.send(requestData);
    });
};

export default axios;
